package utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import constant.Constant;
import entry.Page;

import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;

import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;

import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;



import java.io.*;
import java.util.*;

public class InUtils {
    public static int width = 330;
    public static int height = 260;
    public static int twoWidth = 120;
    public static float pt = 72f/25.4f;
    public static String titile = "说明书自动拼版";




    public static void createPdfByInfo(Info info) {

        float jiaoxian = info.getJj();
        float jiaoxianjubian = info.getJx();
        float space = info.getSpace();

        String company = info.getCompany();
        String model = info.getModel();
        int weight = info.getWeight();
        String  material= info.getMaterial();
        int pageCount = info.getPageCount();
        int num = info.getNum();
        float width = info.getWidth();
        float height = info.getHeight();
        int col = info.getCol();
        int row = info.getRow();
        String binding = info.getBinding();
        String lian = info.getLian();
        String path = info.getPath();
        String yinshuafangshi = info.getPinbanfangshi();
        int bigNumber = num;
        int lianshu = info.getLianshu();

        bigNumber /=lianshu;

        int dan_tao_ban_ye_shu = 0;

        if(yinshuafangshi.equals(Constant.yin_shua_fang_shi_zheng_fan)){

            //如果 正反版 单套版的最大页数 = 列数x行数x2
            dan_tao_ban_ye_shu = col*row*2;

        }else if(yinshuafangshi.equals(Constant.yin_shua_fang_shi_zi_fan)){

            //如果自翻版 单套版的最大页数 = 列数x行数
            dan_tao_ban_ye_shu = col*row;
            bigNumber /=2;
        }
        // bigNumber 整除情况下都对

        dan_tao_ban_ye_shu = dan_tao_ban_ye_shu/lianshu;
        if(row%lianshu!=0){
            ItextUtil.alert("输入的行数不能整除联数!\n联数是"+lianshu+",行数必须是"+lianshu+"的整数倍!",titile);
            return;
        }

        if(binding.equals("骑马钉")){
            List<Page> pages = QiMaDingUtil.getPages(pageCount, dan_tao_ban_ye_shu);
            float pageWidth = (jiaoxian+Constant.chuxue)*2+col*width+space*(col/2-1);
            float pageHeight = (jiaoxian+Constant.chuxue)*2 + row*height+space*(row-1);
            zheng_hao_zheng_chu(info, company, model, weight, material, pageCount, binding, lian, path, yinshuafangshi, bigNumber, (int) pageWidth, (int) pageHeight,pages);

        }else if(binding.equals("胶装")){
            List<Page> pages = JiaoZhuangUtil.getPages(pageCount, dan_tao_ban_ye_shu);
            jiaozhuang(info, company, model, weight, material, pageCount, binding, lian, path, yinshuafangshi, bigNumber, pages);
        }




    }

    public static void jiaozhuang(Info info, String company, String model, int weight, String material, int pageCount, String binding, String lian, String path, String yinshuafangshi, int bigNumber, List<Page> pages) {
        int in = 0;
        String yinshuafangshi2 = yinshuafangshi;
        int lianshu2 = info.getLianshu();
        for(Page page:pages){
            in++;
            float jj = info.getJj();//脚线距边
            float jx = info.getJx();//脚线长度
            int col = info.getCol();
            int row = info.getRow();
            float width = info.getWidth();
            float height = info.getHeight();
            float space = info.getSpace();
            info.setLianshu(lianshu2);

            float pageWidth = (jj+jx)*2+width*col+space*(col-1);
            float pageHeight = (jj+jx)*2+height*row+space*(row-1);
            if(in==1){
                pageWidth = (jj+jx)*2+width*col+space*(col/2-1)+col/2.0f*(pageCount-4)/2.0f*0.1f;
                pageHeight = (jj+jx)*2+height*row+space*(row-1);
            }
            //如果页数能整出 单套页数
            List<Integer> list = page.getPages();
            int lianshu = info.getLianshu();
            if(yinshuafangshi.equals(Constant.yin_shua_fang_shi_zheng_fan)){
                if(page.getMultiple()!=1){
                    if(page.getMultiple()==2){
                        yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
                    }else if(page.getMultiple()==4){
                        yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
                        lianshu +=2;
                    }else if(page.getMultiple()==8){
                        yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
                        lianshu +=4;
                    }
                }else{
                    yinshuafangshi2 = Constant.yin_shua_fang_shi_zheng_fan;
                }
            }else{
                yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
            }

            //北大青鸟80g双胶纸【骑马钉16-16】【自翻印】(20张)《100x100》
            String outPath ="";

            if(pageWidth>pageHeight){
                outPath = company+weight+"G"+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+pages.size()+"-"+in+"】"+"【"+yinshuafangshi2+"】"+
                        "("+(int)(bigNumber/page.getMultiple())+"张)"+"《"+ (int)pageWidth +"x"+ ((int)pageHeight+4) +"》《"+info.getCol()+"x"+info.getRow()+"》《"+model+"》.pdf";
                if(weight==0){
                    outPath = company+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+pages.size()+"-"+in+"】"+"【"+yinshuafangshi2+"】"+"("+(int)(bigNumber/page.getMultiple())+"张)"+
                            "《"+ (int)pageWidth +"x"+ ((int)pageHeight +4)+"》《"+info.getCol()+"x"+info.getRow()+"》《"+model+"》.pdf";
                }

            }else{
                outPath = company+weight+"G"+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+pages.size()+"-"+in+"】"+"【"+yinshuafangshi2+"】"+
                        "("+(int)(bigNumber/page.getMultiple())+"张)"+"《"+ (int)pageHeight +"x"+((int)pageWidth+4)  +"》《"+model+"》《"+info.getCol()+"x"+info.getRow()+"》.pdf";
                if(weight==0){
                    outPath = company+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+pages.size()+"-"+in+"】"+"【"+yinshuafangshi2+"】"+"("+(int)(bigNumber/page.getMultiple())+"张)"+
                            "《"+  (int)pageHeight +"x"+((int)pageWidth+4)  +"》《"+model+"》《"+info.getCol()+"x"+info.getRow()+"》.pdf";
                }

            }



            outPath = new File(path).getParent()+"/"+outPath;
            String tempPdfPath = "info/temp2.pdf";
            createPdfByPages(list,path,tempPdfPath);
            info.setPageCount(list.size());
            info.setIndex(in);
            info.setOutPath(outPath);
            info.setPath(tempPdfPath);
            info.setLianshu(lianshu);
            info.setPinbanfangshi(yinshuafangshi2);
//            break;
            Imposition.jiaozhuang(info,pageCount);
        }


    }

    /**
     * 正好整除的情况下
     * @param info
     * @param company
     * @param model
     * @param weight
     * @param material
     * @param pageCount
     * @param binding
     * @param lian
     * @param path
     * @param yinshuafangshi
     * @param bigNumber
     * @param pageWidth
     * @param pageHeight
     */

    public static void zheng_hao_zheng_chu(Info info, String company, String model, int weight, String material, int pageCount, String binding, String lian, String path, String yinshuafangshi, int bigNumber, int pageWidth, int pageHeight, List<Page> pages) {
        String yinshuafangshi2 = yinshuafangshi;
        int lianshu2 = info.getLianshu();
        for(Page page:pages){
            //如果页数能整出 单套页数
            info.setLianshu(lianshu2);
            List<Integer> list = page.getPages();
            int lianshu = info.getLianshu();

            if(yinshuafangshi.equals(Constant.yin_shua_fang_shi_zheng_fan)){
                if(page.getMultiple()!=1){
                    if(page.getMultiple()==2){
                        yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
                    }else if(page.getMultiple()==4){
                        yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
//                        lianshu =page.getMultiple();
                    }else if(page.getMultiple()==8){
                        yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
//                        lianshu +=2;
                    }
                }else{
                    yinshuafangshi2 = Constant.yin_shua_fang_shi_zheng_fan;
                }
            }else{
                yinshuafangshi2 = Constant.yin_shua_fang_shi_zi_fan;
            }
            if(Constant.qiang_zhi_zheng_fan){
                yinshuafangshi2 = Constant.yin_shua_fang_shi_zheng_fan;
            }
            //北大青鸟80g双胶纸【骑马钉16-16】【自翻印】(20张)《100x100》
            String outPath ="";
            if(pageWidth>pageHeight){
                outPath = company+weight+"G"+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+yinshuafangshi2+"】"+
                        "("+(int)(bigNumber/page.getMultiple())+"张)"+"《"+ pageWidth +"x"+ (pageHeight+4) +"》《"+info.getCol()+"x"+info.getRow()+"》《"+model+"》.pdf";
                if(weight==0){
                    outPath = company+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+yinshuafangshi2+"】"+"("+(int)(bigNumber/page.getMultiple())+"张)"+
                            "《"+ pageWidth +"x"+ (pageHeight+4) +"》《"+info.getCol()+"x"+info.getRow()+"》《"+model+"》.pdf";
                }

            }else{
                outPath = company+weight+"G"+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+yinshuafangshi2+"】"+
                        "("+(int)(bigNumber/page.getMultiple())+"张)"+"《"+ pageHeight +"x"+(pageWidth+4)  +"》《"+model+"》《"+info.getCol()+"x"+info.getRow()+"》.pdf";
                if(weight==0){
                    outPath = company+material+"【"+lian+binding+pageCount+"-"+list.size()+"】"+"【"+yinshuafangshi2+"】"+"("+(int)(bigNumber/page.getMultiple())+"张)"+
                            "《"+  pageHeight +"x"+(pageWidth+4)  +"》《"+model+"》《"+info.getCol()+"x"+info.getRow()+"》.pdf";
                }

            }



            outPath = new File(path).getParent()+"/"+outPath;
            String tempPdfPath = "info/temp2.pdf";
            createPdfByPages(list,path,tempPdfPath);
            info.setPageCount(list.size());
            info.setOutPath(outPath);
            info.setPath(tempPdfPath);
            info.setLianshu(lianshu);
            info.setPinbanfangshi(yinshuafangshi2);
//            break;

            Imposition.qimading(info);
        }

    }




    public static void createPdfByPages(List<Integer>list,String inPath,String outPath){


        try{

            PdfReader reader  = new PdfReader(inPath);
            Rectangle cropBox = reader.getCropBox(1);
            float pageWidth = cropBox.getWidth();
            float pageHeight = cropBox.getHeight();
            Document document = new Document(new Rectangle(pageWidth, pageHeight));//新建一个文档并且设置页面大小
            FileOutputStream outputStream =  new FileOutputStream(outPath);//新建一个pdf文档;
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);//把新建的pdf 赋值给 document
            writer.setBoxSize("trim", new Rectangle(Constant.chuxue * pt, Constant.chuxue * pt, pageWidth - Constant.chuxue * pt, pageHeight - Constant.chuxue * pt));
            writer.setPdfVersion(PdfWriter.VERSION_1_5);
            document.open();//打开 document文档
            PdfContentByte cb = writer.getDirectContent();
            for(int i:list){
                document.newPage();
                PdfImportedPage importedPage = writer.getImportedPage(reader, i);
                cb.addTemplate(importedPage,0,0);
            }
            outputStream.flush();//关闭文件
            document.close();//关闭文件
            outputStream.close();//关闭文件
            reader.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public  static void showMessage(String title,String message){
        final Stage dialog = new Stage() ;
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(Constant.primaryStage);
        FlowPane dialogVbox = new FlowPane();
        dialogVbox.setPadding(new Insets(5));
        TextArea textArea = new TextArea(message);
        textArea.setPrefWidth(280);
        textArea.setPrefHeight(180);
        textArea.setWrapText(true);
        dialogVbox.getChildren().add(textArea);
        Scene dialogScene = new Scene(dialogVbox,300,200);
        dialog.setScene(dialogScene);
        dialog.getIcons().add(Constant.ico);
        dialog.setTitle(title);
        dialog.setResizable(false);
        dialog.show();
    }


    public  static void peiZhi(String title){
         Stage dialog = new Stage() ;
        dialog.getIcons().add(Constant.ico);
        dialog.setTitle(Constant.titile);
//        dialog.initModality(Modality.APPLICATION_MODAL);
//        dialog.initOwner(Constant.primaryStage);
//        FlowPane dialogVbox = new FlowPane();
//        dialogVbox.setPadding(new Insets(5));
//        TextArea textArea = new TextArea(message);
//        textArea.setPrefWidth(280);
//        textArea.setPrefHeight(180);
//        textArea.setWrapText(true);
//        dialogVbox.getChildren().add(textArea);
//        Scene dialogScene = new Scene(dialogVbox,300,200);
//        dialog.setScene(dialogScene);
//        dialog.getIcons().add(Constant.ico);
//        dialog.setTitle(title);
//        dialog.setResizable(false);
//        dialog.show();

        final Parent parent;
        try {
            Constant.peizhiStage = dialog;
            File file = new File("info/fxml/PeiZhiViewer.fxml");
            parent = FXMLLoader.load(file.toURI().toURL());
            dialog.setScene(new Scene(parent,Constant.width, 100));
            dialog.show();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        peiZhi("");
    }


    public static void wenjianmingduquguizhe(String s) {


        Stage dialog = new Stage() ;
        dialog.getIcons().add(Constant.ico);
        dialog.setTitle(Constant.titile);
        dialog.setWidth(940);
        dialog.setHeight(750);

        final Parent parent;
        try {
            Constant.peizhiStage = dialog;
            File file = new File("info/fxml/WenJianMingViewer.fxml");
            parent = FXMLLoader.load(file.toURI().toURL());
            dialog.setScene(new Scene(parent));
            dialog.show();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
